/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef SHARED_BASE_THREAD_WIN32_H_
#define SHARED_BASE_THREAD_WIN32_H_

#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <process.h>


class Runnable;

class ThreadImpl
{
public:
	typedef DWORD   ID;

	enum Priority
	{
		PRIO_LOWEST_IMPL  = THREAD_PRIORITY_LOWEST,
		PRIO_LOW_IMPL     = THREAD_PRIORITY_BELOW_NORMAL,
		PRIO_NORMAL_IMPL  = THREAD_PRIORITY_NORMAL,
		PRIO_HIGH_IMPL    = THREAD_PRIORITY_ABOVE_NORMAL,
		PRIO_HIGHEST_IMPL = THREAD_PRIORITY_HIGHEST
	};

	ThreadImpl(Runnable *runnable);
	~ThreadImpl(void);

	bool startImpl(void);
	void joinImpl(void);
	bool joinableImpl(void);

	bool setPriorityImpl(int priority);

	ID idImpl(void) const;

	static ID currentThreadIdImpl(void);
	static void sleepImpl(long miliseconds);

private:
	static unsigned int __stdcall proc(void* arg);

	ID _id;
	::uintptr_t _handle;
	Runnable *_runnable;
};


inline bool ThreadImpl::setPriorityImpl(int priority)
{
	return SetThreadPriority((HANDLE)_handle, priority) != FALSE;
}

inline ThreadImpl::ID ThreadImpl::idImpl(void) const
{
	return _id;
}

inline ThreadImpl::ID ThreadImpl::currentThreadIdImpl(void)
{
	return GetCurrentThreadId();
}

inline void ThreadImpl::sleepImpl(long miliseconds)
{
	Sleep((DWORD)(miliseconds));
}

#endif /* SHARED_BASE_THREAD_WIN32_H_ */
